package org.sjs.dreamfly.biz.news

import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.ViewModelProvider
import org.json.JSONObject
import org.sjs.dreamfly.app.MainActivity
import org.sjs.dreamfly.app.PlayInfoLoadedEvent
import org.sjs.dreamfly.app.defaultEventBus
import org.sjs.dreamfly.browser.BrowserConst
import org.sjs.dreamfly.browser.PhemonWebView
import org.sjs.dreamfly.browser.WebViewFragment
import org.sjs.dreamfly.common.base.BaseActivity
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.common.util.Router
import org.sjs.dreamfly.model.ModelUtils
import org.sjs.dreamfly.model.VideoInfo

class NewsFragment: WebViewFragment() {
    companion object {
        fun newInstance(url: String = NewsConstants.HOME_URL_TOU_TIAO,
                        point: Int = BrowserConst.InjectPoint.POINT_ON_PROGRESS_MORE_THAN_1
        ): NewsFragment {
            return NewsFragment().apply {
                arguments = Bundle().apply {
                    putString("url", url)
                    putInt("point", point)
                }
            }
        }
    }

    private var sniffer: Sniffer? = null
    private lateinit var viewModel: NewsViewModel

    override fun onInitViewModel() {
        viewModel = ViewModelProvider(requireActivity())[NewsViewModel::class.java]
    }

    override fun onLoadData() {
        showLoadingView()
        useWebViewMask(true)
        webViewClientAcceptVisitor(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                LogUtil.d("url:${request?.url.toString()}")
                return if (NewsConstants.HOME_URL_TOU_TIAO == request?.url.toString()) {
                    super.shouldOverrideUrlLoading(view, request)
                } else {
                    if (activity is MainActivity) {
                        Router.launchNewsDetail(request?.url.toString())
                        true
                    } else {
                        super.shouldOverrideUrlLoading(view, request)
                    }
                }
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                LogUtil.d("url:$url")
                (activity as? BaseActivity)?.hideLoadingView()
                view?.url?.let {
                    if (NewsUtil.isVideoNews(it)) {
                        useWebViewMask(true)
                    } else {
                        useWebViewMask(false)
                    }
                }

                loadingView.postDelayed({ hideLoadingView() }, 800)
                super.onPageFinished(view, url)
            }

            override fun onLoadResource(view: WebView?, url: String?) {
                super.onLoadResource(view, url)
                if (NewsUtil.isVideoNews(view?.url?:"")) {
                    if (url?.startsWith("https://m.toutiao.com/related/open/") == true) {
                        LogUtil.d("url:$url")
                        viewModel.loadMore(url)
                    } else if (ModelUtils.isXiGuaVideoUrl(url)) {
                        LogUtil.d("url:$url, originUrl:${view?.originalUrl}")
                        sniffer?.next(view?.originalUrl?:"", url!!)
                        if (view?.originalUrl == arguments?.getString("url")) {
                            PlayInfoLoadedEvent(VideoInfo(videoUrl = url, refer = view?.originalUrl),
                                PlayInfoLoadedEvent.FROM_NATIVE).apply {
                                defaultEventBus.post(this)
                            }
                        }
                    }
                }
            }
        })
        arguments?.getString("url")?.let { loadUrl(it) }
    }

    fun snifferVideoInfo(list: List<VideoInfo>) {
        if (sniffer == null) {
            sniffer = Sniffer(list, webView = getDefaultWebView())
        } else {
            sniffer?.append(list)
        }
        sniffer?.run()
    }

    class Sniffer(list: List<VideoInfo>, val webView: PhemonWebView) {
        fun run() {
            if (waitingList.isNotEmpty()) {
                waitingList.first().refer?.let {
                    LogUtil.d("waiting:${waitingList.size}, sniffed:${sniffedList.size}, url:$it")
                    webView.loadUrl(it)
                }
            } else {
                webView.loadUrl("about:blank")
                webView.clearHistory()
            }

        }

        fun next(pageUrl: String, resourceUrl: String) {
            LogUtil.d("pageUrl:$pageUrl, resourceUrl:$resourceUrl")
            waitingList.find { it.refer == pageUrl }?.let {
                waitingList.remove(it)
                it.videoUrl = resourceUrl
                sniffedList.add(it)
                run()
            }
        }

        fun append(list: List<VideoInfo>) {
            var count = 0
            list.forEach { item->
                if (waitingList.find { it->
                    item.title == it.title
                } == null) {
                    waitingList.add(item)
                    count++
                }
            }
            LogUtil.d("append:$count")
        }

        private val sniffedList = mutableListOf<VideoInfo>()
        private val waitingList = list.toMutableList()
    }

}